package com.dylan.历史.多线程.并发编程的艺术.锁;

import com.dylan.历史.util.LogUtil;
import com.dylan.历史.util.SleepUtils;

/**
 * Created by Dylan on 2018/9/19.
 */
public class MultiLockTest {

    public static void main(String[] args) {
        new Thread(new Runner(5000), "Thread-1").start();
        SleepUtils.milliseconds(200);
        new Thread(new Runner(4000), "Thread-2").start();
        SleepUtils.milliseconds(200);
        new Thread(new Runner(1000), "Thread-3").start();
        SleepUtils.milliseconds(200);
        new Thread(new Runner(2000), "Thread-4").start();
        SleepUtils.milliseconds(200);
        new Thread(new Runner(5000), "Thread-5").start();
        SleepUtils.milliseconds(200);
        new Thread(new Runner(5000), "Thread-6").start();
        SleepUtils.milliseconds(200);
        new Thread(new Runner(5000), "Thread-7").start();
    }

    private static MultiLock lock = new MultiLock(3);

    private static class Runner implements Runnable {

        private long milliseconds;

        Runner(long milliseconds) {
            this.milliseconds = milliseconds;
        }

        @Override
        public void run() {
            LogUtil.info("准备获取锁");
            lock.lock();
            try {
                LogUtil.info("获取到了锁");
                SleepUtils.milliseconds(milliseconds);
            } finally {
                LogUtil.info("释放了锁");
                lock.unlock();
            }
        }
    }
}
